<template>
    <div id="orders">
        <h2>我的订单</h2>
        <div v-if="paginatedOrders.length">
            <div v-for="order in paginatedOrders" :key="order.id" class="order">
                <div class="order-header">
                    <h3>订单号：{{ order.id }}</h3>
                    <p>日期：{{ order.date | formatDate }}</p>
                </div>
                <div class="order-summary">
                    <p>总金额：<span class="order-summary-value">{{ order.totalPrice | moneyFormat }}</span></p>
                    <p>总数量：<span class="order-summary-value">{{ order.totalAmount }}</span></p>
                </div>
                <div class="item-list">
                    <h4>商品列表：</h4>
                    <ul>
                        <li v-for="item in order.items" :key="item.goods_id" class="item">
                            <img :src="item.thumb_url" alt="商品图片" class="item-image">
                            <div class="item-info">
                                <p class="item-name">{{ item.goods_name }}</p>
                                <p class="item-price">{{ item.price | moneyFormat }} x {{ item.buy_count }}件</p>
                                <el-button type="text" @click="openReviewDialog(order, item)">评价</el-button>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <div v-else>
            <p>暂无订单</p>
        </div>
        <div class="pagination-container">
            <el-pagination v-if="orders.length" @current-change="handlePageChange" :current-page="currentPage"
                :page-size="pageSize" layout="total, prev, pager, next" :total="orders.length">
            </el-pagination>
        </div>

        <!-- 评价对话框 -->
        <el-dialog :visible.sync="reviewDialogVisible" title="评价商品">
            <div>
                <h3>{{ reviewItem.goods_name }}</h3>
                <el-rate v-model="review.rating" :colors="colors" show-score text-color="#ff9900"></el-rate>
                <el-input type="textarea" autosize placeholder="请输入内容" v-model="review.text"></el-input>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="reviewDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitReview">提交</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import { postComment, addGoodsToCart, createOrder } from '@/api/index';


export default {
    data() {
        return {
            currentPage: 1,
            pageSize: 5,
            reviewDialogVisible: false,
            review: {
                rating: 0,
                text: ''
            },
            reviewOrder: {},
            reviewItem: {},
            colors: ['#99A9BF', '#F7BA2A', '#FF9900']
        };
    },
    computed: {
        ...mapState(['orders']),
        paginatedOrders() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.orders.slice(start, end);
        }
    },
    mounted() {
        let user_id = this.$store.state.userInfo.id;
        console.log('Dispatching getOrders with user_id:', user_id);
        this.$store.dispatch('getOrders', user_id).then(() => {
            console.log('Orders after dispatch:', JSON.stringify(this.orders, null, 2));
            this.$forceUpdate();
        });
    },
    methods: {
        handlePageChange(page) {
            this.currentPage = page;
        },
        openReviewDialog(order, item) {
            this.reviewOrder = order;
            this.reviewItem = item;
            this.reviewDialogVisible = true;
        },
        async submitReview() {
            const result = await postComment(this.reviewItem.goods_id, this.review.text, this.review.rating, this.$store.state.userInfo.id);
            if (result.success_code === 200) {
                this.$message.success('评价成功');
                this.reviewDialogVisible = false;
                this.review.rating = 0;
                this.review.text = '';
                // 更新商品评论
                this.$store.dispatch('reqGoodsComment', { goodsId: this.reviewItem.goods_id });
            } else {
                this.$message.error('评价失败');
            }
        }
    },
    filters: {
        moneyFormat(value) {
            return '¥' + parseFloat(value).toFixed(2);
        },
        formatDate(value) {
            if (!value) return '';
            const date = new Date(value);
            const options = {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            };
            return date.toLocaleDateString('zh-CN', options).replace(/\//g, '-');
        }
    }
}
</script>

<style scoped>
#orders {
    margin: 0 auto;
    padding: 20px;
    background: #f3f4f6;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.order {
    background: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
    margin-bottom: 15px;
}

.order-header h3 {
    margin: 0;
    font-size: 1.5em;
}

.order-header p {
    margin: 0;
    color: #888;
}

.order-summary {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    margin-bottom: 15px;
}

.order-summary p {
    margin: 0;
    font-weight: bold;
}

.order-summary-value {
    color: #f56c6c;
}

.item-list h4 {
    margin-bottom: 10px;
    color: #333;
}

ul {
    list-style: none;
    padding: 0;
}

.item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
}

.item:last-child {
    border-bottom: none;
}

.item-image {
    width: 100px;
    height: 100px;
    border-radius: 8px;
    object-fit: cover;
    margin-right: 15px;
}

.item-info {
    flex: 1;
}

.item-name {
    font-size: 1.2em;
    margin: 0;
    color: #333;
}

.item-price {
    margin: 5px 0 0;
    color: #888;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.el-pagination {
    font-size: 16px;
}

.el-pagination .el-pager li {
    font-size: 16px;
    width: 35px;
    height: 35px;
    line-height: 35px;
}

.el-pagination .el-pagination__total,
.el-pagination .el-pagination__jump,
.el-pagination .el-pagination__rightwrapper {
    font-size: 16px;
}

.el-pagination .el-select .el-input__inner {
    font-size: 16px;
    height: 35px;
    line-height: 35px;
}
</style>
